package com.copyctrl.campus.portal.service.Impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.copyctrl.campus.common.constant.RedisConstant;
import com.copyctrl.campus.portal.service.UserService;
import com.copyctrl.mapper.CampUserMapper;
import com.copyctrl.model.CampUser;
import com.copyctrl.model.CampUserExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author:JH
 * @version:1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    CampUserMapper campUserMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public int insertUser(CampUser user) {
        int i = campUserMapper.insert(user);
        return i;
    }

    @Override
    public CampUser findUserByOpenId(String openId) {
        String json = stringRedisTemplate.opsForValue().get(RedisConstant.USER_KEY + openId);
        CampUser user=new CampUser();
        if (StrUtil.isBlank(json)){
            CampUserExample user1=new CampUserExample();
            user1.createCriteria().andOpenidEqualTo(openId);
            List<CampUser> campUsers = campUserMapper.selectByExample(user1);
            user=campUsers.size()==0?null:campUsers.get(0);
        }else {
            user=JSONUtil.toBean(json,CampUser.class);
        }
        return user;
    }

    @Override
    public boolean updateUser(CampUser user) {
        int i = campUserMapper.updateByPrimaryKey(user);
        if (i==1){
            stringRedisTemplate.opsForValue().set(RedisConstant.USER_KEY+user.getOpenid(),JSONUtil.toJsonStr(user));
        }
        return i==1?true:false;
    }
}
